package com.service;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;

import com.code.CallHistory;
import com.code.Main;
import com.code.Service_ShowCusDetail;
import com.database.DBCallHistory;
import com.database.DBSystem;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Bundle;
import android.os.IBinder;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.Toast;

public class MyService extends Service {
	TelephonyManager telephonyManager;
	PhoneStateListener listener;
	Boolean isRunging = false;
	Boolean isIdle = false;
	private static final String TAG = "MyService";
	private DBSystem dbHelper;
	public static Boolean insert;

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		return START_STICKY;
	}

	@Override
	public void onCreate() {

		Log.d(TAG, "onCreate");
		Toast.makeText(this, "Đã mở chương trình bắt số", Toast.LENGTH_LONG)
				.show();
		// Get the telephony manager
		telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);

		// Create a new PhoneStateListener
		listener = new PhoneStateListener() {

			public void onCallStateChanged(int state, String incomingNumber) {
				switch (state) {
				case TelephonyManager.CALL_STATE_RINGING:
					if (insertCuocGoiToSQLSERVER(incomingNumber)) {
						// Toast.makeText(
						// MyService.this,
						// "�?ã kết nối S�?T " + incomingNumber
						// + " vào TiHaGas", Toast.LENGTH_LONG)
						// .show();
						Log.d(TAG, "->" + incomingNumber);
						isRunging = true;
					} else
						// Toast.makeText(
						// MyService.this,
						// "Không thể kết nối S�?T " + incomingNumber
						// + " vào TiHaGas", Toast.LENGTH_LONG)
						// .show();
						Log.d(TAG, "x" + incomingNumber);
					break;
				case TelephonyManager.CALL_STATE_IDLE:
					// Toast.makeText(MyService.this, "Thao tác",
					// Toast.LENGTH_SHORT).show();
					isRunging = false;
					break;
				case TelephonyManager.CALL_STATE_OFFHOOK:
					// Toast.makeText(MyService.this, "�?ã bắt máy",
					// Toast.LENGTH_SHORT).show();
					isRunging = false;
					break;
				default:
					break;
				}
			}
		};

		// Register the listener with the telephony manager
		telephonyManager.listen(listener, PhoneStateListener.LISTEN_CALL_STATE);
	}

	@Override
	public void onDestroy() {
		Toast.makeText(this, "Đã tắt chương trình bắt số", Toast.LENGTH_LONG)
				.show();
		Log.d(TAG, "onDestroy");
		// Remove the listener with the telephony manager
		telephonyManager.listen(listener, PhoneStateListener.LISTEN_NONE);
	}

	public void onStart(Intent intent, int startid) {
		Toast.makeText(this, "Đã mở chương trình bắt số", Toast.LENGTH_LONG)
				.show();
		Log.d(TAG, "onStart");
	}

	public Boolean insertCuocGoiToSQLSERVER(String phoneNumber) {
		Connection conn = null;

		// edit by tranng date 03/04/2014
		String isInsert = "";
		// get value isinsert
		SharedPreferences shareFrDbName = this.getSharedPreferences(
				"insert_call", MODE_WORLD_WRITEABLE);
		if (shareFrDbName != null) {
			isInsert = shareFrDbName.getString("isinsert", "");// get value to
																// shareFrDbName
		}

		if (isInsert.equals("Y"))
			insert = true;
		else
			insert = false;
		try {
			String driver = "net.sourceforge.jtds.jdbc.Driver";
			Class.forName(driver).newInstance();

			dbHelper = new DBSystem(this);
			dbHelper.open();
			Cursor cur = dbHelper.SelectSystemAll();
			String strServerName = "";
			String strServerNameWifi = "";
			String strServerPort = "";
			String strLogin = "";
			String strPassword = "";
			String strDatabaseName = "";
			String strChiNhanh = "";
			String strServerName3G = "";
			String strStatusServerName = "";
			Boolean checkRS = false;
			if (cur != null) {
				while (cur.moveToNext()) {
					strServerNameWifi = cur.getString(1).toString();
					strServerPort = cur.getString(2).toString();
					strLogin = cur.getString(3).toString();
					strPassword = cur.getString(4).toString();
					strDatabaseName = cur.getString(5).toString();
					strChiNhanh = cur.getString(8).toString();
					strServerName3G = cur.getString(9).toString();
					strStatusServerName = cur.getString(10).toString();
				}
				cur.close();
			}
			dbHelper.close();
			if (strStatusServerName.equals("wifi")) {
				strServerName = strServerNameWifi;
			} else {
				strServerName = strServerName3G;
			}
			String url = "jdbc:jtds:sqlserver://" + strServerName + ":"
					+ strServerPort + ";DatabaseName=" + strDatabaseName
					+ ";integratedSecurity=true;user=" + strLogin
					+ ";password=" + strPassword + "";
			conn = DriverManager.getConnection(url);
			Statement stmt = conn.createStatement();
			if (!isRunging && insert)
				stmt.execute("spInsertCuocGoiByMobile '" + phoneNumber + "','"
						+ strChiNhanh + "' ");

			// load Name, Address
			String strName = "";
			String strAddress = "";
			String strMaSP = "";
			PreparedStatement pstmt = conn
					.prepareStatement("SELECT TOP 1 [Company Name] AS Name, SO+', '+Duong+', '+Quan+', '+Tinh AS [Address], MaSP "
							+ "FROM Suppliers "
							+ "WHERE Phone LIKE '%"
							+ phoneNumber
							+ "%' OR DTDD LIKE '%"
							+ phoneNumber
							+ "%' OR SoDT1 LIKE '%"
							+ phoneNumber
							+ "%' OR SoDT2 LIKE '%" + phoneNumber + "%'");
			pstmt.execute();
			ResultSet rs = pstmt.getResultSet();
			while (rs.next()) {
				if (rs.getString("Name") != null)
					strName = rs.getString("Name").toString();
				if (rs.getString("Address") != null)
					strAddress = rs.getString("Address").toString();
				if (rs.getString("MaSP") != null)
					strMaSP = rs.getString("MaSP").toString();
				Toast.makeText(
						this,
						"Tên: " + strName + "\nĐịa chỉ: " + strAddress
								+ "\nMaSP: " + strMaSP, Toast.LENGTH_LONG)
						.show();
				Toast.makeText(
						this,
						"Tên: " + strName + "\nĐịa chỉ: " + strAddress
								+ "\nMaSP: " + strMaSP, Toast.LENGTH_LONG)
						.show();
				Toast.makeText(
						this,
						"Tên: " + strName + "\nĐịa chỉ: " + strAddress
								+ "\nMaSP: " + strMaSP, Toast.LENGTH_LONG)
						.show();

				checkRS = true;

			}
			// edit by trangbm date 05/04/2013
			if (!checkRS) {
				
				DBCallHistory dbCalHis = new DBCallHistory(this);

				ArrayList<String> valueSeach = GoogleSearch
						.getValueToGoogleSearch(phoneNumber);
				if (valueSeach != null && valueSeach.size() > 0) {
					showCallAndSaveInfomation(valueSeach, phoneNumber, dbCalHis);
				}
				//search phone by : (@MaVung) Number
				else {
					String tmp = phoneNumber.substring(0, 2).toString();
					String tmpNumber = phoneNumber.substring(2,
							phoneNumber.length()).toString();
					if (!tmp.equals("01") && !tmp.equals("09")) {
						String tNewPhone = "(" + tmp + ")" + tmpNumber;
						ArrayList<String> valueSeachNewPhone = GoogleSearch
								.getValueToGoogleSearch(tNewPhone);
						if (valueSeachNewPhone != null
								&& valueSeachNewPhone.size() > 0) {
							showCallAndSaveInfomation(valueSeachNewPhone, phoneNumber, dbCalHis);
						} 
						//search phone by : @MaVung . Number
						else {
							tNewPhone = tmp + "." + tmpNumber;
							valueSeachNewPhone = GoogleSearch
									.getValueToGoogleSearch(tNewPhone);
							if (valueSeachNewPhone != null
									&& valueSeachNewPhone.size() > 0) {
								showCallAndSaveInfomation(valueSeachNewPhone, phoneNumber, dbCalHis);

							}
							//search phone by : @MaVung - Number
							else
							{
								tNewPhone = tmp + "-" + tmpNumber;
								valueSeachNewPhone = GoogleSearch
										.getValueToGoogleSearch(tNewPhone);
								if (valueSeachNewPhone != null
										&& valueSeachNewPhone.size() > 0) {
									showCallAndSaveInfomation(valueSeachNewPhone, phoneNumber, dbCalHis);
								}
							}//end 
						}
					}
				}
			}
			pstmt.close();
			conn.close();
			return true;
		} catch (Exception e) {
			Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
			return false;
		}
	}

	/**
	 * @author trangbm
	 * @param valueSeach
	 * @param phoneNumber
	 * @param dbCalHis
	 */
	public void showCallAndSaveInfomation(ArrayList<String> valueSeach,String phoneNumber,DBCallHistory dbCalHis)
	{
		for(int i =0;i<valueSeach.size();i++){
		Toast.makeText(this, valueSeach.get(i),
				Toast.LENGTH_LONG).show();
		}
		dbCalHis.open();
		int id = dbCalHis
				.InsertCallHistory(phoneNumber);
		for (int i = 0; i < valueSeach.size(); i++) {
			dbCalHis.InsertCallHistoryDetail(String
					.valueOf(id), valueSeach
					.get(i).toString());
		}
		dbCalHis.close();
	}
}
